package com.demo.validation.param_validation;

import com.demo.validation.custom.Letter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * @author ayatsuji
 * @date 2021-06-13 23:51
 * @since
 *
 * 在Controller参数校验按以下步骤：
 * Controller类注解@Validated
 * 方法参数加上需要的注解即可
 */
@Validated
@RestController
@RequestMapping("param")
public class ParamValidationDemo {

    // 字符串校验
    @GetMapping("q1")
    public String q1(@NotBlank String name) {
        // @NotBlank等同与@NotEmpty，没传参或者参数为空串都会报错
        // 而@NotNull允许参数为空串，仅在没传参时报错
        // 违反会抛javax.validation.ConstraintViolationException
        return name;
    }

    // 整型校验
    @GetMapping("q2")
    public Integer q2(Integer age) {
        // 关于类型适配： 传参类型错误的话会抛org.springframework.web.method.annotation.MethodArgumentTypeMismatchException, 比如传age=abc
        return age;
    }
    @GetMapping("q3")
    public Integer[] q3(@NotEmpty Integer[] age) {
        // @NotNull在不传参时报错，而@NotEmpty在参数为空和不传参时报错
        // 抛异常javax.validation.ConstraintViolationException
        return age;
    }

    @GetMapping("q4")
    public Integer q4(@Validated Age age) {
        // 这里传参age小于12会抛出org.springframework.validation.BindException，因为是用一个实体类来接收参数
        // 如果直接按q5写抛的就是javax.validation.ConstraintViolationException
        return age.age;
    }

    @GetMapping("q5")
    public Integer q5(@Min(12) Integer age) {
        return age;
    }

    public static class Age {
        @Min(value = 12, message = "不能小于12") Integer age;

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
    }

    @GetMapping("q6")
    public String q6(@Letter String val) {
        return "q6";
    }
}
